package edu.cuit.avatar.io;

import java.io.*;

/**
 * @author <a href="mailto:1020zhaodan@163.com">Adan</a>
 * @version 1.0
 * @date 2025/7/11 15:17
 */
public class WriteData {
    public static void main(String[] args) {
        var file = new File("peppa.txt");
        writeByPrintWriter(file);
    }

    /**
     * 使用字符输出流FileWriter(节点流)向文件写内容
     * @param file 目标文件
     */
    public static void writeByFileWriter(File file){
        Writer out = null;
        try {
            out = new FileWriter(file);
            out.write("100");
            out.write("\r\n");
            out.write("name: 小猪Peppa");

            //out.flush(); //将输出流中的内容刷新到目标文件
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //最终确保流(资源)的关闭释放
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 使用PrintWriter向文本文件书写内容
     * 采用 try-with-resource自动关闭资源
     * @param file
     */
    public static void writeByPrintWriter(File file){
        try(var out = new PrintWriter(file)){
            out.print("Pig Peppa ");
            out.println(5); //输出完成后换行
            out.print("Elephant Emily ");
            out.println(5);
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}
